package com.ideabove.heart.alarm;

import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;

import com.ideabove.heart.db.DBHelper;
import com.ideabove.heart.db.Database;
import com.ideabove.heart.util.LogUtil;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class BootService extends Service {

    private final String TAG = "BootService";

    @Override
    public IBinder onBind(final Intent intent) {
            return null;
    }

    @Override
    public void onCreate() {
            super.onCreate();
    }

    @Override
    public void onStart(final Intent intent, final int startId) {
            super.onStart(intent, startId);

            

//            Toast toast = Toast.makeText(this, "!@#$$!$@!$@!$@!##$@!$",Toast.LENGTH_LONG); 
//            toast.show(); 
            
            LoadAlarmsFromDatabase();

    }

    private void LoadAlarmsFromDatabase() {
    	DBHelper dbHelper = new DBHelper(this);		
    	Hashtable <String,String>info = dbHelper.getAlarmInfo();
    	
    	String hour = info.get(Database.AlarmSetTable.HOUR);
    	String min = info.get(Database.AlarmSetTable.MIN);
    	

    	
    	Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR));
		calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
		calendar.set(Calendar.MINUTE,	Integer.parseInt(min));
		calendar.set(Calendar.SECOND, 0);
				
		
		long setTime = Long.parseLong(info.get(Database.AlarmSetTable.SETTIME));
		
//		Toast toast = Toast.makeText(this, setTime +":" + calendar.getTimeInMillis(), Toast.LENGTH_LONG); 
//        toast.show(); 
		
		if(calendar.getTimeInMillis() < setTime){ // 나중에			
			updateAlarm(setTime);
			
		}else{ // 이미지나간 알람일경우 하루 뒤로 세팅한다.
			setTime = calendar.getTimeInMillis() + (60 * 1000 * 60 * 24);
			updateAlarm(setTime);
		}		
    	
    }

    private static int ARARM_INDEX = 337213;
    
    private void updateAlarm(long settime) {		

		
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceiver.class);
        
        Date today = new Date();
        today.setTime(settime);
        
        PendingIntent sender = PendingIntent.getBroadcast(
        		this, ARARM_INDEX, intent, PendingIntent.FLAG_CANCEL_CURRENT);        
        
        am.setRepeating(
        	AlarmManager.RTC_WAKEUP,
        	settime,
        	AlarmManager.INTERVAL_DAY, sender
        );
        
//        Toast toast = Toast.makeText(this, "D:" + today.getDate() + "H:" + today,Toast.LENGTH_LONG); 
//        toast.show(); 
        
	}
}
